﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;
using DevExpress.Web.ASPxUploadControl;
using System.Drawing;
using System.Security.Cryptography;
using System.Drawing.Imaging;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Web.UI;
using org.in2bits.MyXls;
using System.Data;
using System.Text.RegularExpressions;

namespace ElingOA6_Admin_DSJCJ.Common
{
    public class GenerateUtil
    {

        /// <summary>
        /// 去除HTML标签，获取文字
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本  
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML  
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([/r/n])[/s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "/xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "/xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "/xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "/xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(/d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("/r/n", "");
            //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="foldername">相对路径</param>
        public static void addfolder(string foldername)
        {
            //获取文件夹绝对路径
            try
            {
                string url = HttpContext.Current.Server.MapPath(foldername);
                //如果不存在该文件夹就创建
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 返回当前服务器路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath(Page p)
        {
            //string servername=HttpContext.Current.Request.ServerVariables["Server_Name"];
            //string serverport = HttpContext.Current.Request.ServerVariables["Server_Port"];
            //if (serverport == "80")
            //{
            //    serverport = "";
            //}
            //else
            //{
            //    serverport = ":" + serverport;

            //}
            //string serverAndPort = "http://"+servername + serverport;
            ////string serverAndPort = "http://" + HttpContext.Current.Request.Url.Authority;
            //string strRoot = HttpContext.Current.Request.ApplicationPath;
            //if (strRoot != "/")
            //{
            //    strRoot += "/";
            //}
            //return serverAndPort + strRoot;
            return p.ResolveUrl("~/");
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">绝对路径</param>
        public static void DeleteFileJD(string file)
        {
            if (file.Length == 0) return;
            if (System.IO.File.Exists(file))
                System.IO.File.Delete(file);
        }



        /// <summary>
        /// 获取客户端IP地址(ipv4)
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型

                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
        private static string GetClientIP()
        {
            if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"])
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
        }
        /// <summary>
        /// 获取客户端ip地址
        /// </summary>
        /// <returns></returns>
        public static string GetClientIPv4Address()
        {
            string ipv4 = String.Empty;

            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }

            if (ipv4 != String.Empty)
            {
                return ipv4;
            }
            // 利用 Dns.GetHostEntry 方法，由获取的 IPv6 位址反查 DNS 纪录，
            // 再逐一判断何者为 IPv4 协议，即可转为 IPv4 位址。
            foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList)
            //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }

            return ipv4;
        }


        #region 验证码
        private static int letterWidth = 20;//单个字体的宽度范围

        private static int letterHeight = 20;//单个字体的高度范围

        // private static int letterCount = 4;//验证码位数

        private static char[] chars = "123456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz".ToCharArray();
        private static string[] fonts = { "Arial", "Georgia" };
        /// <summary>
        /// 产生波形滤镜效果
        /// </summary>
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;
        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        public static byte[] CreateValidateGraphic(string checkCode)
        {

            int int_ImageWidth = checkCode.Length * letterWidth;
            Random newRandom = new Random();
            Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器

                Random random = new Random();
                //白色背景
                g.Clear(System.Drawing.Color.White);
                //画图片的背景噪音线

                for (int i = 0; i < 10; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
                }

                //画图片的前景噪音点

                for (int i = 0; i < 10; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
                }
                //随机字体和颜色的验证码字符


                int findex;
                for (int int_index = 0; int_index < checkCode.Length; int_index++)
                {
                    findex = newRandom.Next(fonts.Length - 1);
                    string str_char = checkCode.Substring(int_index, 1);
                    Brush newBrush = new SolidBrush(GetRandomColor());
                    Point thePos = new Point(int_index * letterWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
                    g.DrawString(str_char, new System.Drawing.Font(fonts[findex], 12, FontStyle.Bold), newBrush, thePos);
                }
                //灰色边框
                g.DrawRectangle(new Pen(System.Drawing.Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
                //图片扭曲
                // image = TwistImage(image, true, 3, 4);
                //将生成的图片发回客户端

                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
            finally
            {
                //Response.ClearContent(); //需要输出图象信息 要修改HTTP头 
                //Response.ContentType = "image/Png";
                //Response.BinaryWrite(ms.ToArray());
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高，一般为3</param>
        /// <param name="dPhase">波形的起始相位，取值区间[0-2*PI)</param>
        /// <returns></returns>
        private static System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);

            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);

            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;

                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;

                    dx += dPhase;

                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;

                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;

                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            return destBmp;
        }
        private static System.Drawing.Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

            //  为了在白色背景上显示，尽量生成深色

            //int int_Red = RandomNum_First.Next(256);
            //int int_Green = RandomNum_Sencond.Next(256);
            //int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            //int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            int int_Red = RandomNum_First.Next(180);
            int int_Green = RandomNum_Sencond.Next(180);
            int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue);
        }
        //  生成随机数字字符串

        public static string GetRandomNumberString(int int_NumberLength)
        {
            Random random = new Random();
            string validateCode = string.Empty;
            for (int i = 0; i < int_NumberLength; i++)
                validateCode += chars[random.Next(0, chars.Length)].ToString();
            return validateCode;
        }
        #endregion

        #region 指定密钥加密

        /// <summary>
        /// 使用给定密钥字符串加密string
        /// </summary>
        /// <param name="original">原始文字</param>
        /// <param name="fieldName">字段名字</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>密文</returns>
        public static string Encrypt(string original, string fieldName)
        {
            fieldName = fieldName.ToUpper();
            string key = "ELINGSOFT" + fieldName;

            byte[] buff = System.Text.Encoding.Default.GetBytes(original);
            byte[] kb = System.Text.Encoding.Default.GetBytes(key);
            return Convert.ToBase64String(Encrypt(buff, kb));
        }
        /// <summary>
        /// 使用给定密钥加密
        /// </summary>
        /// <param name="original">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        private static byte[] Encrypt(byte[] original, byte[] key)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = MakeMD5(key);
            des.Mode = CipherMode.ECB;

            return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
        }
        /// <summary>
        /// 生成MD5摘要
        /// </summary>
        /// <param name="original">数据源</param>
        /// <returns>摘要</returns>
        private static byte[] MakeMD5(byte[] original)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            byte[] keyhash = hashmd5.ComputeHash(original);
            hashmd5 = null;
            return keyhash;
        }

        #endregion
        #region 指定密钥解密
        /// <summary>
        /// 使用缺省密钥字符串解密string
        /// </summary>
        /// <param name="original">密文</param>
        /// <returns>明文</returns>
        public static string Decrypt(string original, string fieldName)
        {
            fieldName = fieldName.ToUpper();
            original = original.Replace(" ", "+");//空格替换加号，加号在query string是保留用来代表空格的
            return Decrypt(original, "ELINGSOFT" + fieldName, System.Text.Encoding.Default);
        }
        /// <summary>
        /// 使用给定密钥字符串解密string,返回指定编码方式明文
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>明文</returns>
        private static string Decrypt(string encrypted, string key, Encoding encoding)
        {
            byte[] buff = Convert.FromBase64String(encrypted);
            byte[] kb = System.Text.Encoding.Default.GetBytes(key);
            return encoding.GetString(Decrypt(buff, kb));
        }
        /// <summary>
        /// 使用给定密钥解密数据
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        private static byte[] Decrypt(byte[] encrypted, byte[] key)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = MakeMD5(key);
            des.Mode = CipherMode.ECB;

            return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
        }
        #endregion


        /// <summary>
        /// 生成字符串型唯一ID
        /// </summary>
        /// <returns></returns>
        public static string GenerateStringId()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            string result = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + string.Format("{0:x}", i - DateTime.Now.Ticks);
            return result;
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="foldername">相对路径</param>
        public static void Addfolder(string foldername)
        {
            //获取文件夹绝对路径
            try
            {
                string url = HttpContext.Current.Server.MapPath(foldername);
                //如果不存在该文件夹就创建
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fu">HttpPostedFile文件对象</param>
        /// <param name="url">文件夹路径</param>
        /// <returns></returns>
        public static string UploadImage(UploadedFile fu, string url)
        {

            if (fu.ContentLength <= 0)
            {
                return "1";//文件内容为空
            }

            //获取文件类型、大小、名称

            string type = fu.ContentType;
            int size = fu.ContentLength;
            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

            if (type != "image/bmp" && type != "image/gif" && type != "image/pjpeg" && type != "image/x-png" && type != "image/jpg")
            {
                return "2";//上传类型不是图片
            }

            if (size > 10 * 1024 * 1024)
            {
                return "3";//超出大小10M
            }

            //获取文件的扩展名
            string extension = Path.GetExtension(fu.FileName).ToLower();
            //改变图片名称
            string strnewFileNmae = GenerateUtil.GenerateStringId();
            //判断图片保存文件夹是否存在
            GenerateUtil.Addfolder(url);
            string fullpath = HttpContext.Current.Server.MapPath(url) + "/" + strnewFileNmae + extension;

            //判断是否存在相同的文件
            if (File.Exists(fullpath) == true)
            {
                return "4";//文件已存在

            }
            //上传文件到硬盘
            fu.SaveAs(fullpath);
            return strnewFileNmae + extension;//文件名称
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fu">HttpPostedFile文件对象</param>
        /// <param name="url">文件夹路径</param>
        /// <returns></returns>
        public static string UploadImage(HttpPostedFileBase fu, string url)
        {

            if (fu.ContentLength <= 0)
            {
                return "1";//文件内容为空
            }

            //获取文件类型、大小、名称

            string type = fu.ContentType;
            int size = fu.ContentLength;
            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

            if (type != "image/bmp" && type != "image/gif" && type != "image/pjpeg" && type != "image/x-png" && type != "image/jpg")
            {
                return "2";//上传类型不是图片
            }

            if (size > 10 * 1024 * 1024)
            {
                return "3";//超出大小10M
            }

            //获取文件的扩展名
            string extension = Path.GetExtension(fu.FileName).ToLower();
            //改变图片名称
            string strnewFileNmae = GenerateUtil.GenerateStringId();
            //判断图片保存文件夹是否存在
            GenerateUtil.Addfolder(url);
            string fullpath = HttpContext.Current.Server.MapPath(url) + "/" + strnewFileNmae + extension;

            //判断是否存在相同的文件
            if (File.Exists(fullpath) == true)
            {
                return "4";//文件已存在

            }
            //上传文件到硬盘
            fu.SaveAs(fullpath);
            return strnewFileNmae + extension;//文件名称
        }
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="fu">HttpPostedFile文件对象</param>
        /// <param name="url">文件夹路径</param>
        /// <param name="url">文件名称(默认为空)</param>
        /// <returns></returns>
        public static string UploadFile(HttpPostedFileBase fu, string url, string filename = "")
        {

            if (fu.ContentLength <= 0)
            {
                return "1";//文件内容为空
            }

            //获取文件类型、大小、名称

            string type = fu.ContentType;
            int size = fu.ContentLength;
            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

            //if (size > 100 * 1024 * 1024)
            //{
            //    return "3";//超出大小100M
            //}

            //获取文件的扩展名
            string extension = Path.GetExtension(fu.FileName).ToLower();
            //改变文件名称
            string strnewFileName = "";
            if (filename == "")
            {
                strnewFileName = GenerateUtil.GenerateStringId();
            }
            else
            {
                strnewFileName = filename;
            }

            //判断图片保存文件夹是否存在
            GenerateUtil.Addfolder(url);
            string fullpath = HttpContext.Current.Server.MapPath(url) + "/" + strnewFileName + extension;

            //判断是否存在相同的文件
            if (File.Exists(fullpath) == true)
            {
                return "4";//文件已存在

            }
            //上传文件到硬盘
            fu.SaveAs(fullpath);
            return strnewFileName + extension;//文件名称
        }
        /// <summary>
        /// 上传信息类文件
        /// </summary>
        /// <param name="fu"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        //public static string UploadDocFile(HttpPostedFileBase fu, string url, ref Model.SystemNoticeAttach docAttachModel, string docDesc)
        //{
        //    if (fu.ContentLength <= 0)
        //    {
        //        return "1";//文件内容为空
        //    }

        //    //获取文件类型、大小、名称
        //    string type = fu.ContentType;
        //    int size = fu.ContentLength;
        //    string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

        //    //获取文件的扩展名
        //    string extension = Path.GetExtension(fu.FileName).ToLower();
        //    //switch (extension)
        //    //{
        //    //    case ".jpg": type = "image/pjpeg"; break;
        //    //    case ".gif": type = "image/gif"; break;
        //    //    case ".bmp": type = "image/bm;"; break;
        //    //    case ".png": type = "image/x-png"; break;
        //    //}


        //    //if (type != "image/bmp" && type != "image/gif" && type != "image/pjpeg" && type != "image/x-png" && type != "image/jpg")
        //    //{
        //    //    return "2";//上传类型不是图片
        //    //}

        //    if (size > 100 * 1024 * 1024)
        //    {
        //        return "3";//超出大小100M
        //    }

        //    //改变附件名称
        //    string strnewFileNmae = GenerateUtil.GenerateStringId();
        //    //判断附件保存文件夹是否存在
        //    GenerateUtil.Addfolder(url);
        //    string fullpath = HttpContext.Current.Server.MapPath(url) + "/" + strnewFileNmae + extension;

        //    //判断是否存在相同的文件
        //    if (File.Exists(fullpath) == true)
        //    {
        //        return "4";//文件已存在
        //    }
        //    //上传文件到硬盘
        //    fu.SaveAs(fullpath);

        //    docAttachModel.FAttachSvrFileName = url + "/" + strnewFileNmae + extension;
        //    docAttachModel.FAttachOldFileName = factFileName + extension;
        //    //获取文件二进制格式
        //    System.IO.Stream stream = fu.InputStream;
        //    byte[] buffer = new byte[stream.Length];
        //    stream.Read(buffer, 0, (int)stream.Length);
        //    stream.Close();
        //    docAttachModel.FAttachContent = buffer;
        //    docAttachModel.FAttachFileExt = type;

        //    if (docDesc == "")
        //    {
        //        docAttachModel.FAttachDesc = factFileName;
        //    }
        //    else
        //    {
        //        docAttachModel.FAttachDesc = docDesc;
        //    }
        //    return strnewFileNmae + extension;//文件名称
        //}


        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="_strOldFile">旧文件相对路径</param>
        /// <param name="_strNewFile">新文件相对路径</param>
        public static void CopyFile(string _strOldFile, string _strNewFile)
        {
            if (_strOldFile.Length == 0) return;
            _strOldFile = System.Web.HttpContext.Current.Server.MapPath(_strOldFile);
            _strNewFile = System.Web.HttpContext.Current.Server.MapPath(_strNewFile);
            if (System.IO.File.Exists(_strOldFile))
                System.IO.File.Copy(_strOldFile, _strNewFile);
        }



        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="_strOldFile">旧文件绝对路径</param>
        /// <param name="_strNewFile">新文件绝对路径</param>
        public static void CopyFileAbsolute(string _strOldFile, string _strNewFile)
        {
            if (_strOldFile.Length == 0 || _strNewFile.Length == 0) return;
            if (System.IO.File.Exists(_strOldFile))
                System.IO.File.Copy(_strOldFile, _strNewFile);
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">此地路径相对程序路径而言</param>
        public static void DeleteFile(string file)
        {
            if (file.Length == 0) return;
            if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(file)))
                System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(file));
        }
        /// <summary>
        /// 获取配置文件appSettings的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfigValue(string key)
        {
            string value = "";
            if (ConfigurationManager.AppSettings[key] != null)
            {
                value = ConfigurationManager.AppSettings[key].ToString();
            }
            return value;
        }
        /// <summary>
        /// 身份证15位转18位
        /// </summary>
        /// <param name="idCardNo"></param>
        /// <returns></returns>
        public static string IDCard15To18(string idCardNo)
        {
            string _idCardNo = "";
            if (idCardNo.Length == 15)
            {
                int[] wi = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
                char[] ai = new char[] { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
                string ls_re = "";
                ls_re = idCardNo.Substring(0, 6) + "19" + idCardNo.Substring(6, 9);
                int ll_sum = 0;
                char ll_code = ' ';
                for (int i = 0; i < 17; i++)
                {
                    ll_sum += wi[i] * int.Parse(ls_re.Substring(i, 1));
                    ll_code = ai[ll_sum % 11];
                }
                ls_re += ll_code;

                _idCardNo = ls_re;
            }
            return _idCardNo;

        }

        /// <summary>
        /// 身份证18位转15位
        /// </summary>
        /// <param name="idCardNo"></param>
        /// <returns></returns>
        public static string IDCard18To15(string idCardNo)
        {
            string _idCardNo = "";
            if (idCardNo.Length == 18)
            {
                string ls_re = "";
                ls_re = idCardNo.Substring(0, 6) + idCardNo.Substring(8, 9);
                _idCardNo = ls_re;
            }
            return _idCardNo;

        }
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="file">相对路径</param>
        /// <returns></returns>
        public static bool ExistsFile(string file)
        {
            try
            {
                if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(file)))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 解析fckEditor路径(IIS创建的是虚拟目录)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetPath(string strPath)
        {
            string ImagePath = ConfigurationManager.AppSettings["FCKeditor:BasePath"].ToString();
            int t = ImagePath.IndexOf("fckeditor");
            if (t != -1)
            {
                string xnmumc = ImagePath.Substring(0, t - 1);
                int t1 = strPath.IndexOf(xnmumc);
                if (t1 != -1)
                {
                    int xnLength = xnmumc.Length;
                    if (t1 == 0)
                    {
                        return strPath.Substring(xnLength);
                    }
                    else
                    {
                        return (strPath.Substring(0, t1) + strPath.Substring(t1 + xnLength));
                    }

                }

            }
            return strPath;
        }
        /// <summary>
        /// 把long型转换成字符串形式的IP地址
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public static String LongToIP(long para)
        {
            Int64 ip = Convert.ToInt64(para);
            String str = "";
            str += ip % 256;
            ip /= 256;
            str = ip % 256 + "." + str;
            ip /= 256;
            str = ip % 256 + "." + str;
            ip /= 256;
            str = ip % 256 + "." + str;
            return str;
        }

        /// <summary>
        /// 导出excel通用方法
        /// <creator>sunlj</creator>
        /// <date>2013-10-18</date>
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="excelTitle"></param>
        /// <param name="rowCount"></param>
        /// <param name="xlsxlsModelList"></param>
        public static Byte[] ExportToExcelReturnPath1(string filename, string excelTitle, int rowCount, List<Model.XlsModel> xlsxlsModelList, List<Model.XlsModel_Column> xlsColList, List<Model.XlsModel_Row> xlsRowList)
        {
            //string _filepath = "";
            filename = filename.Replace(".xls", "");
            filename += Guid.NewGuid();
            if (xlsxlsModelList.Count > 0)
            {
                int _tmpRowNum = xlsxlsModelList[0].RowIndex;
                int _colCount = 0;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    if (_xlsModel.RowIndex == _tmpRowNum)
                    {
                        _colCount += _xlsModel.ColSpan;
                    }
                }

                DataTable dt = new DataTable();

                for (int i = 0; i < _colCount; i++)
                {
                    dt.Columns.Add(i.ToString());

                }
                for (int i = 0; i < rowCount; i++)
                {
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < _colCount; j++)
                    {
                        dr[j] = "0";
                    }
                    dt.Rows.Add(dr);

                }


                XlsDocument doc = new XlsDocument();
                doc.FileName = filename;
                Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
                //列设置
                if (xlsColList != null)
                {
                    foreach (Model.XlsModel_Column xlsCol in xlsColList)
                    {
                        ColumnInfo colInfo = new ColumnInfo(doc, sheet);//生成列格式对象
                        colInfo.ColumnIndexStart = xlsCol.ColumnIndexStart;
                        colInfo.ColumnIndexEnd = xlsCol.ColumnIndexEnd;
                        colInfo.Width = xlsCol.Width;
                        sheet.AddColumnInfo(colInfo);
                    }
                }
                //行设置
                if (xlsRowList != null)
                {
                    foreach (Model.XlsModel_Row xlsRow in xlsRowList)
                    {
                        RowInfo rol = new RowInfo();
                        rol.RowIndexStart = xlsRow.RowIndexStart;
                        rol.RowIndexEnd = xlsRow.RowIndexEnd;
                        rol.RowHeight = xlsRow.RowHeight;
                        sheet.AddRowInfo(rol);
                    }
                }

                XF cellXF = doc.NewXF();//标题
                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                Cell cell = sheet.Cells.Add(1, 1, excelTitle, cellXF);
                MergeArea meaA = new MergeArea(1, 1, 1, _colCount);
                sheet.AddMergeArea(meaA);//填加合并单元格

                int _rownumber = 1;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    DataRow _dr = dt.Rows[_xlsModel.RowIndex - 1];
                    int _colindex = 1;
                    int _rowindex = _xlsModel.RowIndex;

                    for (int i = 0; i < _dr.ItemArray.Length; i++)
                    {
                        if (_dr.ItemArray[i].ToString() == "0")
                        {
                            _colindex = i + 1;
                            break;
                        }

                    }

                    cellXF = doc.NewXF();//内容
                    cellXF.TextWrapRight = true; //自动换行
                    cellXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中  
                    cellXF.UseBorder = true;
                    cellXF.TopLineStyle = 1;
                    cellXF.TopLineColor = Colors.Black;
                    cellXF.BottomLineStyle = 1;
                    cellXF.BottomLineColor = Colors.Black;
                    cellXF.LeftLineStyle = 1;
                    cellXF.LeftLineColor = Colors.Black;
                    cellXF.RightLineStyle = 1;
                    cellXF.RightLineColor = Colors.Black;

                    switch (_xlsModel.HAlign)
                    {
                        case Model.XlsModel.HorizontalAlign.Left:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Left;//设定文字居左
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Center:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Right:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Right;//设定文字居右
                                break;
                            }

                    }

                    switch (_xlsModel.TitleType)
                    {
                        case Model.XlsModel.ContentType.String:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                        case Model.XlsModel.ContentType.Number:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, Convert.ToDouble(_xlsModel.Title), cellXF);
                                break;
                            }
                        default:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                    }
                    dt.Rows[_rowindex - 1][_colindex - 1] = "1";

                    if (_xlsModel.RowSpan > 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _xlsModel.ColSpan + _colindex - 1);
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";
                            }
                            for (int i = 1; i < _xlsModel.RowSpan; i++)
                            {
                                dt.Rows[_rowindex - 1 + i][_colindex] = "1";
                            }
                        }
                        else
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex);
                        }
                        //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex, _colindex);
                        //sheet.AddMergeArea(meaA);//填加合并单元格
                        for (int i = 1; i < _xlsModel.RowSpan; i++)
                        {
                            dt.Rows[_rowindex - 1 + i][_colindex - 1] = "1";
                        }

                    }

                    if (_xlsModel.RowSpan == 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {

                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber, _colindex + _xlsModel.ColSpan - 1);
                            //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber, _colindex, _colindex + _xlsModel.ColSpan - 1);
                            //sheet.AddMergeArea(meaA);//填加合并单元格
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";

                            }


                        }
                    }


                }

                // doc.Send();
                //addfolder("~/tempfile")

                // string _mappath = GetServerMapPath("~/tempfile");
                //doc.Save(_mappath, true);
                //_filepath = "/tempfile/" + doc.FileName;
                //if (!ExistsFile("/tempfile/elingsoft_delete.txt"))
                //{
                //    FileStream fs = File.Create(_mappath + "/elingsoft_delete.txt");
                //    fs.Close();

                //}
                return doc.Bytes.ByteArray;
                //doc.Send();

                //HttpContext.Current.Response.Flush();
                //HttpContext.Current.Response.End();

            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 导出excel通用方法
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="excelTitle"></param>
        /// <param name="rowCount"></param>
        /// <param name="xlsxlsModelList"></param>
        public static void ExportToExcelReturnPath(string filename, string excelTitle, int rowCount, List<Model.XlsModel> xlsxlsModelList, List<Model.XlsModel_Column> xlsColList, List<Model.XlsModel_Row> xlsRowList)
        {
            //string _filepath = "";
            filename = filename.Replace(".xls", "");
            filename += Guid.NewGuid();
            if (xlsxlsModelList.Count > 0)
            {
                int _tmpRowNum = xlsxlsModelList[0].RowIndex;
                int _colCount = 0;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    if (_xlsModel.RowIndex == _tmpRowNum)
                    {
                        _colCount += _xlsModel.ColSpan;
                    }
                }

                DataTable dt = new DataTable();

                for (int i = 0; i < _colCount; i++)
                {
                    dt.Columns.Add(i.ToString());

                }
                for (int i = 0; i < rowCount; i++)
                {
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < _colCount; j++)
                    {
                        dr[j] = "0";
                    }
                    dt.Rows.Add(dr);

                }


                XlsDocument doc = new XlsDocument();
                doc.FileName = filename;
                Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
                //列设置
                if (xlsColList != null)
                {
                    foreach (Model.XlsModel_Column xlsCol in xlsColList)
                    {
                        ColumnInfo colInfo = new ColumnInfo(doc, sheet);//生成列格式对象
                        colInfo.ColumnIndexStart = xlsCol.ColumnIndexStart;
                        colInfo.ColumnIndexEnd = xlsCol.ColumnIndexEnd;
                        colInfo.Width = xlsCol.Width;
                        sheet.AddColumnInfo(colInfo);
                    }
                }
                //行设置
                if (xlsRowList != null)
                {
                    foreach (Model.XlsModel_Row xlsRow in xlsRowList)
                    {
                        RowInfo rol = new RowInfo();
                        rol.RowIndexStart = xlsRow.RowIndexStart;
                        rol.RowIndexEnd = xlsRow.RowIndexEnd;
                        rol.RowHeight = xlsRow.RowHeight;
                        sheet.AddRowInfo(rol);
                    }
                }

                XF cellXF = doc.NewXF();//标题
                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                Cell cell = sheet.Cells.Add(1, 1, excelTitle, cellXF);
                MergeArea meaA = new MergeArea(1, 1, 1, _colCount);
                sheet.AddMergeArea(meaA);//填加合并单元格

                int _rownumber = 1;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    DataRow _dr = dt.Rows[_xlsModel.RowIndex - 1];
                    int _colindex = 1;
                    int _rowindex = _xlsModel.RowIndex;

                    for (int i = 0; i < _dr.ItemArray.Length; i++)
                    {
                        if (_dr.ItemArray[i].ToString() == "0")
                        {
                            _colindex = i + 1;
                            break;
                        }

                    }

                    cellXF = doc.NewXF();//内容
                    cellXF.TextWrapRight = true; //自动换行
                    cellXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中  
                    cellXF.UseBorder = true;
                    cellXF.TopLineStyle = 1;
                    cellXF.TopLineColor = Colors.Black;
                    cellXF.BottomLineStyle = 1;
                    cellXF.BottomLineColor = Colors.Black;
                    cellXF.LeftLineStyle = 1;
                    cellXF.LeftLineColor = Colors.Black;
                    cellXF.RightLineStyle = 1;
                    cellXF.RightLineColor = Colors.Black;

                    switch (_xlsModel.HAlign)
                    {
                        case Model.XlsModel.HorizontalAlign.Left:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Left;//设定文字居左
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Center:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Right:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Right;//设定文字居右
                                break;
                            }

                    }

                    switch (_xlsModel.TitleType)
                    {
                        case Model.XlsModel.ContentType.String:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                        case Model.XlsModel.ContentType.Number:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, Convert.ToDouble(_xlsModel.Title), cellXF);
                                break;
                            }
                        default:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                    }
                    dt.Rows[_rowindex - 1][_colindex - 1] = "1";

                    if (_xlsModel.RowSpan > 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _xlsModel.ColSpan + _colindex - 1);
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";
                            }
                            for (int i = 1; i < _xlsModel.RowSpan; i++)
                            {
                                dt.Rows[_rowindex - 1 + i][_colindex] = "1";
                            }
                        }
                        else
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex);
                        }
                        //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex, _colindex);
                        //sheet.AddMergeArea(meaA);//填加合并单元格
                        for (int i = 1; i < _xlsModel.RowSpan; i++)
                        {
                            dt.Rows[_rowindex - 1 + i][_colindex - 1] = "1";
                        }

                    }

                    if (_xlsModel.RowSpan == 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {

                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber, _colindex + _xlsModel.ColSpan - 1);
                            //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber, _colindex, _colindex + _xlsModel.ColSpan - 1);
                            //sheet.AddMergeArea(meaA);//填加合并单元格
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";

                            }


                        }
                    }


                }

                // doc.Send();
                //addfolder("~/tempfile")

                // string _mappath = GetServerMapPath("~/tempfile");
                //doc.Save(_mappath, true);
                //_filepath = "/tempfile/" + doc.FileName;
                //if (!ExistsFile("/tempfile/elingsoft_delete.txt"))
                //{
                //    FileStream fs = File.Create(_mappath + "/elingsoft_delete.txt");
                //    fs.Close();

                //}
                doc.Send();
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();

            }
        }

        /// <summary>
        /// 合并行列的方法
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="xf"></param>
        /// <param name="title"></param>
        /// <param name="startRow"></param>
        /// <param name="startCol"></param>
        /// <param name="endRow"></param>
        /// <param name="endCol"></param>
        private static void MergeRegion(ref Worksheet ws, XF xf, string title, int startRow, int startCol, int endRow, int endCol)
        {
            for (int i = startCol; i <= endCol; i++)
            {
                for (int j = startRow; j <= endRow; j++)
                {
                    ws.Cells.Add(j, i, title, xf);
                }
            }
            ws.Cells.Merge(startRow, endRow, startCol, endCol);
        }


        /// <summary>
        /// jcms推送方法
        /// </summary>
        /// <param name="_docObject"></param>
        /// <param name="docClsCd">栏目编号</param>
        /// <returns></returns>
        public static bool PulishToJcms(Model.Document _docObject, string docClsCd)
        {
            string _strXmlUrl = string.Empty;//本地生成的XML地址

            string _strFtpXmlUrl = ConfigurationManager.AppSettings["jcms_FtpXmlUrl"].ToString();

            string _strContentTxt = "";
            string _content = _docObject.FContentTxt;
            try
            {
                //if (istpxw)
                //{
                //    //..............//上传图片
                //    ftpUploadImagertpxw(ref _strContentTxt, _docObject.FDocId);
                //}
                //getHtmlString(ref _strContentTxt);

                _strContentTxt += "<div>&nbsp;&nbsp;&nbsp;&nbsp;" + _content + "</div>";
                FtpUploadImage(ref _strContentTxt);//上传内容中的图片

                FtpUploadAttach(ref _strContentTxt, _docObject.FDocId);//附件上传

                _docObject.FContentTxt = _strContentTxt;

                //这里传递栏目编号，通过数据库获取对应的JCMS编号
                BLL.DocCls docClsBLL = new BLL.DocCls();
                Model.DocCls docClsModel = docClsBLL.GetModel(GlobalConstant.ENTITYNO, docClsCd);
                if (docClsModel != null && docClsModel.FJCMSColID.HasValue)
                {
                    _strXmlUrl = CreateXML(docClsModel.FJCMSColID.Value, _docObject.FTitle, _docObject.FSubTitle, _docObject.FAuthor, _docObject.FContentTxt, _docObject.FPubDate);
                    string _strXmlName = _strXmlUrl.Substring(_strXmlUrl.LastIndexOf('/') + 1);
                    _strFtpXmlUrl += _strXmlName;
                    FtpUploadFile(_strXmlUrl, _strFtpXmlUrl, "xuni");
                }
                //GenerateUtil.DeleteFile(_strXmlUrl);

                // bllpicnews.Updatestatus("Y", _docObject.id);
            }
            catch (Exception)
            {
                if (_strXmlUrl != string.Empty)
                {
                    //GenerateUtil.DeleteFile(_strXmlUrl);
                }

                return false;
            }

            return true;
        }


        //ftp附件上传
        private static void FtpUploadAttach(ref string _strContentTxt, decimal _decDocId)
        {
            string _strFtpAttachUrl = ConfigurationManager.AppSettings["jcms_FtpAttachUrl"].ToString();//ftp上传附件地址
            string _strAttachUrl = ConfigurationManager.AppSettings["jcms_attachUrl"].ToString();//附件实际硬盘保存地址
            string _strAttachName = "";
            string _strFtpUrl = "";
            //Model.pic_news modelpic = bllpicnews.GetModel(_decDocId);
            BLL.DocAttach docAttachBLL = new BLL.DocAttach();
            List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(_decDocId, "DOC");
            if (docAttachList.Count > 0)
            {
                StringBuilder sbr = new StringBuilder();
                sbr.Append("<div>");
                sbr.Append("<table width=\"100%\">");
                sbr.Append("<tr><td align=\"left\" colspan=\"2\"><h3>附件下载</h3></td></tr>");
                sbr.Append("<tr><td width=\"15px\"></td><td></td></tr>");
                foreach (Model.DocAttach model in docAttachList)
                {
                    //_strAttachName = GenerateUtil.GenerateStringId() + GenerateUtil.GetTypeMime(model.FAttachFileExt);

                    _strAttachName = GenerateUtil.GenerateStringId() + model.FAttachSvrFileName.Substring(model.FAttachSvrFileName.LastIndexOf('/') + 1);

                    _strFtpUrl = _strFtpAttachUrl + _strAttachName;

                    byte[] dataByte;
                    FileStream myStream = new FileStream(HttpContext.Current.Server.MapPath(model.FAttachSvrFileName), FileMode.Open, FileAccess.Read);
                    dataByte = new byte[myStream.Length];
                    myStream.Read(dataByte, 0, dataByte.Length);  //写到2进制数组中
                    myStream.Close();

                    GenerateUtil.FtpUploadFileByte(dataByte, _strFtpUrl);
                    sbr.Append("<tr>");
                    sbr.Append("<td><a href=\"");
                    sbr.Append(_strAttachUrl + _strAttachName);
                    sbr.Append("\">");
                    sbr.Append(model.FAttachOldFileName);
                    sbr.Append("</a>");
                    sbr.Append("</td>");
                    sbr.Append("</tr>");
                }

                sbr.Append("</table>");
                sbr.Append("</div>");
                _strContentTxt += sbr.ToString();
            }
        }


        /// <summary>
        ///  ftp上传文件
        /// </summary>
        /// <param name="bytes">文件地址相对路径</param>
        /// <param name="_strFtpFileUrl">ftp 上传的目录地址包括文件名称</param>
        public static void FtpUploadFileByte(byte[] bytes, string _strFtpFileUrl)
        {
            string _strFtpUrl = ConfigurationManager.AppSettings["jcms_FtpUrl"].ToString();
            string _strLogId = ConfigurationManager.AppSettings["jcms_FtpLogID"].ToString();
            string _strPassWord = ConfigurationManager.AppSettings["jcms_FtpPassWord"].ToString();
            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(_strLogId, _strPassWord);

            _strFtpUrl += _strFtpFileUrl;
            request.UploadData(_strFtpUrl, bytes);

        }

        /// <summary>
        /// 根据mime类型返回后缀
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetTypeMime(string type)
        {
            string mime;
            if (type == "application/msexcel")
                mime = ".xls";
            else if (type == "application/msword")
                mime = ".doc";
            else if (type == "application/mspowerpoint")
                mime = ".ppt";
            else if (type == "text/plain")
                mime = ".txt";
            else if (type == "application/octet-stream")
                mime = ".rar";
            else if (type == "application/pdf")
                mime = ".pdf";
            else if (type == "application/zip")
                mime = ".zip";
            else if (type == "image/tiff")
                mime = ".tif";
            else if (type == "application/ocelet-stream")
                mime = ".exe";
            else if (type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                mime = ".docx";
            else if (type == "application/vnd.openxmlformats-officedocument.presentationml.presentation")
                mime = ".pptx";
            else if (type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                mime = ".xlsx";
            else if (type == "image/jpeg")
                mime = ".jpeg";
            else if (type == "image/pjpeg")
                mime = ".jpg";
            else if (type == "image/png")
                mime = ".png";
            else if (type == "image/gif ")
                mime = ".gif";
            else
                mime = "";

            return mime;
        }

        /// <summary>
        /// ftp上传图片
        /// </summary>
        /// <param name="_strContentTxt"></param>
        private  static void FtpUploadImage(ref string _strContentTxt)
        {
            string _strFtpImgUrl = ConfigurationManager.AppSettings["jcms_FtpImgUrl"].ToString();//ftp上传图片地址
            string _strImgUrl = ConfigurationManager.AppSettings["jcms_imgUrl"].ToString();//图片实际硬盘保存地址

            //解析html代码,保存图片以及替换图片位置
            //利用正则
            MatchCollection TDMatchs = Regex.Matches(_strContentTxt,
            "<IMG.*?src=\"(.*?.*?)\".*?>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
           
            for (int i = 0; i < TDMatchs.Count; i++)
            {
                string tmpFtpUrl = "";
                string _picurl = TDMatchs[i].Groups[1].Value;
                string _strPicName = _picurl.Substring(_picurl.LastIndexOf('/') + 1);
                tmpFtpUrl = _strFtpImgUrl + _strPicName;

                GenerateUtil.FtpUploadFile(_picurl, tmpFtpUrl, "xuni");

                _strContentTxt = _strContentTxt.Replace(_picurl, _strImgUrl + _strPicName);

            }
        }


        /// <summary>
        /// ftp上传文件
        /// </summary>
        /// <param name="_strFileUrl">文件地址相对路径</param>
        /// <param name="_strFtpFileUrl">ftp 上传的目录地址包括文件名称</param>
        /// <returns></returns>
        public static void FtpUploadFile(string _strFileUrl, string _strFtpFileUrl, string type)
        {
            string _strFtpUrl = ConfigurationManager.AppSettings["jcms_FtpUrl"].ToString();
            string _strLogId = ConfigurationManager.AppSettings["jcms_FtpLogID"].ToString();
            string _strPassWord = ConfigurationManager.AppSettings["jcms_FtpPassWord"].ToString();

            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(_strLogId, _strPassWord);
            byte[] dataByte;
            if (type == "xuni")
            {
                FileStream myStream = new FileStream(HttpContext.Current.Server.MapPath(_strFileUrl), FileMode.Open, FileAccess.Read);
                dataByte = new byte[myStream.Length];
                myStream.Read(dataByte, 0, dataByte.Length);  //写到2进制数组中
                myStream.Close();
            }
            else
            {
                dataByte = BitmapToBytes(_strFileUrl);
            }

            _strFtpUrl += _strFtpFileUrl;
            request.UploadData(_strFtpUrl, dataByte);
        }

        public static byte[] BitmapToBytes(string photo)
        {
            byte[] images = null;
            Random seed = new Random();
            System.IO.Stream stream = null;
            try
            {

                String fileName = photo.Substring(photo.LastIndexOf("/") + 1);
                String refer = photo.Substring(0, photo.LastIndexOf("/") + 1);
                System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(photo) as System.Net.HttpWebRequest;
                req.AllowAutoRedirect = true;
                req.Referer = refer;

                req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
                System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse;
                stream = res.GetResponseStream();
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                byte[] buffer = new byte[0x1000];
                int bytes;
                while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memoryStream.Write(buffer, 0, bytes);

                }

                images = memoryStream.GetBuffer();

            }
            catch (Exception ex)
            {

                images = null;
            }
            finally
            {
                stream.Close();
            }

            return images;
        }

        /// <summary>
        /// 创建XML文件,用于JCMS推送,返回XML文件地址
        /// </summary>
        /// <param name="_docObject"></param>
        /// <param name="_strColumnid">对应的JCMS栏目ID</param>
        /// <returns></returns>
        public static string CreateXML(int jcmsColumnId, string _strTitle, string _strSubTitle, string _strAuthor, string _strContent, DateTime _strDate)
        {
            string _strWebid = ConfigurationManager.AppSettings["jcms_webid"].ToString();
            string _strEntityName = ConfigurationManager.AppSettings["jcms_EntityName"].ToString();
            int _strColumnid = jcmsColumnId;

            StringBuilder sbr = new StringBuilder();
            sbr.Append("<?xml version='1.0' encoding='UTF-8'?>");
            sbr.AppendLine();
            sbr.Append("<main>");
            sbr.AppendLine();
            sbr.Append("<edition>1.0</edition>");
            sbr.AppendLine();
            sbr.Append("<copyright>大汉网络</copyright>");
            sbr.AppendLine();
            sbr.Append("<article>");
            sbr.AppendLine();
            sbr.Append("<webgroupid><![CDATA[1]]></webgroupid>");
            sbr.AppendLine();

            sbr.Append("<webid><![CDATA[");
            sbr.Append(_strWebid);
            sbr.Append("]]></webid>");
            sbr.AppendLine();

            sbr.Append("<columnid><![CDATA[");
            sbr.Append(_strColumnid.ToString());
            sbr.Append("]]></columnid>");
            sbr.AppendLine();

            sbr.Append("<title><![CDATA[");
            sbr.Append(_strTitle);
            sbr.Append("]]></title>");
            sbr.AppendLine();

            sbr.Append("<caption><![CDATA[");
            sbr.Append(_strEntityName);
            sbr.Append("]]></caption>");
            sbr.AppendLine();

            sbr.Append("<leadtitle><![CDATA[");
            sbr.Append(_strSubTitle);
            sbr.Append("]]></leadtitle>");
            sbr.AppendLine();

            sbr.Append("<linktitle><![CDATA[]]></linktitle>");
            sbr.AppendLine();

            sbr.Append("<author><![CDATA[");
            sbr.Append(_strAuthor);
            sbr.Append("]]></author>");
            sbr.AppendLine();

            sbr.Append("<source><![CDATA[");
            sbr.Append(_strEntityName);
            sbr.Append("]]></source>");
            sbr.AppendLine();

            sbr.Append("<editor><![CDATA[");
            sbr.Append(_strEntityName);
            sbr.Append("]]></editor>");
            sbr.AppendLine();

            sbr.Append("<keyword><![CDATA[]]></keyword>");
            sbr.AppendLine();
            sbr.Append("<describe><![CDATA[]]></describe>");
            sbr.AppendLine();

            sbr.Append("<text><![CDATA[");
            sbr.Append(_strContent);
            sbr.Append("]]></text>");
            sbr.AppendLine();

            sbr.Append("<datetime><![CDATA[");
            sbr.Append(_strDate.ToString("yyyy-MM-dd HH:mm:ss"));
            sbr.Append("]]></datetime>");
            sbr.AppendLine();

            sbr.Append("<image><![CDATA[]]></image>");
            sbr.AppendLine();
            sbr.Append("<flash><![CDATA[]]></flash>");
            sbr.AppendLine();
            sbr.Append("<media><![CDATA[]]></media>");
            sbr.AppendLine();
            sbr.Append("<attach><![CDATA[]]></attach>");
            sbr.AppendLine();
            sbr.Append("</article>");
            sbr.AppendLine();
            sbr.Append("</main>");

            string _strUrl ="/ElingOA6_Admin_DSJCJ/Publish/JcmsXml/";//jcmsXML上传路径
            addfolder(_strUrl);
            _strUrl += GenerateStringId() + ".xml";

            FileInfo fInfo = new FileInfo(HttpContext.Current.Server.MapPath(_strUrl));
            FileStream fs = fInfo.Create();//创建文件

            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            sw.Write(sbr.ToString());
            sw.Close();
            fs.Close();


            return _strUrl;
        }



        /// <summary>
        /// 导出excel通用方法
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="excelTitle"></param>
        /// <param name="rowCount"></param>
        /// <param name="xlsxlsModelList"></param>
        public static Byte[] ExportToExcelReturnPathGetByte(string filename, string excelTitle, int rowCount, List<Model.XlsModel> xlsxlsModelList, List<Model.XlsModel_Column> xlsColList, List<Model.XlsModel_Row> xlsRowList)
        {
            //string _filepath = "";
            filename = filename.Replace(".xls", "");
            filename += Guid.NewGuid();
            if (xlsxlsModelList.Count > 0)
            {
                int _tmpRowNum = xlsxlsModelList[0].RowIndex;
                int _colCount = 0;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    if (_xlsModel.RowIndex == _tmpRowNum)
                    {
                        _colCount += _xlsModel.ColSpan;
                    }
                }

                DataTable dt = new DataTable();

                for (int i = 0; i < _colCount; i++)
                {
                    dt.Columns.Add(i.ToString());

                }
                for (int i = 0; i < rowCount; i++)
                {
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < _colCount; j++)
                    {
                        dr[j] = "0";
                    }
                    dt.Rows.Add(dr);

                }


                XlsDocument doc = new XlsDocument();
                doc.FileName = filename;
                Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
                //列设置
                if (xlsColList != null)
                {
                    foreach (Model.XlsModel_Column xlsCol in xlsColList)
                    {
                        ColumnInfo colInfo = new ColumnInfo(doc, sheet);//生成列格式对象
                        colInfo.ColumnIndexStart = xlsCol.ColumnIndexStart;
                        colInfo.ColumnIndexEnd = xlsCol.ColumnIndexEnd;
                        colInfo.Width = xlsCol.Width;
                        sheet.AddColumnInfo(colInfo);
                    }
                }
                //行设置
                if (xlsRowList != null)
                {
                    foreach (Model.XlsModel_Row xlsRow in xlsRowList)
                    {
                        RowInfo rol = new RowInfo();
                        rol.RowIndexStart = xlsRow.RowIndexStart;
                        rol.RowIndexEnd = xlsRow.RowIndexEnd;
                        rol.RowHeight = xlsRow.RowHeight;
                        sheet.AddRowInfo(rol);
                    }
                }

                XF cellXF = doc.NewXF();//标题
                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                Cell cell = sheet.Cells.Add(1, 1, excelTitle, cellXF);
                MergeArea meaA = new MergeArea(1, 1, 1, _colCount);
                sheet.AddMergeArea(meaA);//填加合并单元格

                int _rownumber = 1;
                foreach (Model.XlsModel _xlsModel in xlsxlsModelList)
                {
                    DataRow _dr = dt.Rows[_xlsModel.RowIndex - 1];
                    int _colindex = 1;
                    int _rowindex = _xlsModel.RowIndex;

                    for (int i = 0; i < _dr.ItemArray.Length; i++)
                    {
                        if (_dr.ItemArray[i].ToString() == "0")
                        {
                            _colindex = i + 1;
                            break;
                        }

                    }

                    cellXF = doc.NewXF();//内容
                    cellXF.TextWrapRight = true; //自动换行
                    cellXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中  
                    cellXF.UseBorder = true;
                    cellXF.TopLineStyle = 1;
                    cellXF.TopLineColor = Colors.Black;
                    cellXF.BottomLineStyle = 1;
                    cellXF.BottomLineColor = Colors.Black;
                    cellXF.LeftLineStyle = 1;
                    cellXF.LeftLineColor = Colors.Black;
                    cellXF.RightLineStyle = 1;
                    cellXF.RightLineColor = Colors.Black;

                    switch (_xlsModel.HAlign)
                    {
                        case Model.XlsModel.HorizontalAlign.Left:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Left;//设定文字居左
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Center:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//设定文字居中
                                break;
                            }
                        case Model.XlsModel.HorizontalAlign.Right:
                            {
                                cellXF.HorizontalAlignment = HorizontalAlignments.Right;//设定文字居右
                                break;
                            }

                    }

                    switch (_xlsModel.TitleType)
                    {
                        case Model.XlsModel.ContentType.String:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                        case Model.XlsModel.ContentType.Number:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, Convert.ToDouble(_xlsModel.Title), cellXF);
                                break;
                            }
                        default:
                            {
                                cell = sheet.Cells.Add(_rowindex + _rownumber, _colindex, _xlsModel.Title, cellXF);
                                break;
                            }
                    }
                    dt.Rows[_rowindex - 1][_colindex - 1] = "1";

                    if (_xlsModel.RowSpan > 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _xlsModel.ColSpan + _colindex - 1);
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";
                            }
                            for (int i = 1; i < _xlsModel.RowSpan; i++)
                            {
                                dt.Rows[_rowindex - 1 + i][_colindex] = "1";
                            }
                        }
                        else
                        {
                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex);
                        }
                        //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber + _xlsModel.RowSpan - 1, _colindex, _colindex);
                        //sheet.AddMergeArea(meaA);//填加合并单元格
                        for (int i = 1; i < _xlsModel.RowSpan; i++)
                        {
                            dt.Rows[_rowindex - 1 + i][_colindex - 1] = "1";
                        }

                    }

                    if (_xlsModel.RowSpan == 1)
                    {
                        if (_xlsModel.ColSpan > 1)
                        {

                            MergeRegion(ref sheet, cellXF, _xlsModel.Title, _rowindex + _rownumber, _colindex, _rowindex + _rownumber, _colindex + _xlsModel.ColSpan - 1);
                            //meaA = new MergeArea(_rowindex + _rownumber, _rowindex + _rownumber, _colindex, _colindex + _xlsModel.ColSpan - 1);
                            //sheet.AddMergeArea(meaA);//填加合并单元格
                            for (int i = 1; i < _xlsModel.ColSpan; i++)
                            {
                                dt.Rows[_rowindex - 1][_colindex - 1 + i] = "1";

                            }


                        }
                    }


                }

                // doc.Send();
                //addfolder("~/tempfile")

                // string _mappath = GetServerMapPath("~/tempfile");
                //doc.Save(_mappath, true);
                //_filepath = "/tempfile/" + doc.FileName;
                //if (!ExistsFile("/tempfile/elingsoft_delete.txt"))
                //{
                //    FileStream fs = File.Create(_mappath + "/elingsoft_delete.txt");
                //    fs.Close();

                //}
                return doc.Bytes.ByteArray;
                //doc.Send();

                //HttpContext.Current.Response.Flush();
                //HttpContext.Current.Response.End();

            }
            else
            {
                return null;
            }
        }



    }
}